package hn.cch.agent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class InstrumentationDemo {

    public static Instrumentation instrumentation;


    // public static void premain(String agentArgs) {
    // public static void agentmain(String agentArgs) {
    public static void premain(String agentArgs, Instrumentation inst) {
    // public static void agentmain(String agentArgs, Instrumentation inst) {
        instrumentation = inst;
        System.out.println("agentArgs:" + agentArgs);
        // try {
        //     inst.retransformClasses(MyClassFileTransformer.class);
        // } catch (UnmodifiableClassException e) {
        //     throw new RuntimeException(e);
        // }
        inst.addTransformer(
            new ClassFileTransformer() {
                @Override
                public byte[] transform(ClassLoader loader, String className,
                                        Class<?> clazz,
                                        ProtectionDomain protectionDomain,
                                        byte[] byteCode) throws IllegalClassFormatException {
                    System.out.println("ClassFileTransformer:" + className);
                    Class[] allLoadedClasses = inst.getAllLoadedClasses();
                    for (Class allLoadedClass : allLoadedClasses) {
                        System.out.println(allLoadedClass.getName());
                    }
                    return byteCode;
                }
            }, true);

    }


}
